if (window == undefined)
{
    let anygloabel = global as any;
    anygloabel["window"] = global;
}

let anywindow = window as any;



namespace letus
{
    function delay(ms: number)
    {
        return new Promise<void>(function (resolve)
        {
            setTimeout(resolve, ms);
        });
    }

    export class require
    {
        static async loadScript(url: string): Promise<void>
        {
            let s: HTMLScriptElement = document.createElement("script");
            s.src = url;
            document.head.appendChild(s);
            let loaded = false;
            s.onload = () =>
            {
                loaded = true;
            }
            s.onerror = (err) =>
            {
                console.error("loadScript Error:" + url);
                throw err;
            }
            while (!loaded)
            {
                await delay(1);
            }
        }
        static DispathWindowOnload(): void
        {
            let _ev = document.createEvent("Event");
            _ev.initEvent("load", true);
            window.dispatchEvent(_ev);
        }
        static MixPath(path: string, requirepath: string): string
        {
            let srcpaths = path.split('/');
            let newpaths = requirepath.split('/');

            //移除空的路径
            for (var j = srcpaths.length - 1; j >= 0; j--)
            {
                if (srcpaths[j] == "")
                {
                    srcpaths = srcpaths.slice(0, srcpaths.length - 1);
                }
            }
            //插入.
            if (srcpaths[0] != "." || srcpaths.length == 0)
            {
                srcpaths.splice(0, 0, ".");
            }

            for (var i = 0; i < newpaths.length; i++)
            {
                let p = newpaths[i];
                if (p == ".")
                    continue;
                else if (p == "..")
                {
                    srcpaths = srcpaths.slice(0, srcpaths.length - 1);
                }
                else
                {
                    srcpaths.push(p);
                }
            }
            return srcpaths.join('/');
        }
        static GetPath(fullurl: string): string
        {
            let pos = fullurl.lastIndexOf("/");
            return fullurl.substring(0, pos);
        }
        static async ParseModule(curpath: string, srctxt: string): Promise<void>
        {
            let lines = srctxt.split('\n');
            for (let i = 0; i < lines.length; i++)
            {
                let line = lines[i];
                let requirepos = line.indexOf("require");
                if (requirepos > 0)
                {
                    let leftcorner = line.indexOf("(", requirepos);
                    let rightcorner = line.indexOf(")", leftcorner);
                    if (leftcorner > 0 && rightcorner > 0)
                    {
                        let name = line.substring(leftcorner + 1, rightcorner);
                        name = name.replace('"', '');
                        name = name.replace("'", "");
                        name = name.replace('"', '');
                        name = name.replace("'", "");
                        let fullurl = require.MixPath(curpath, name);
                        if (this.modules[fullurl] != undefined)//已經擁有的模塊
                            continue;

                        let fullpath = this.GetPath(fullurl);
                        console.log("found import module:" + fullurl + "  in  " + fullpath);
                        let nextfile = await (await fetch(fullurl + ".js")).text();
                        await require.ParseModule(fullpath, nextfile);

                        require.getModulePath = fullpath;
                        //console.log("setpath=" + fullpath);
                        //console.log("loadurl=" + fullurl);


                        let _exports = {};
                        anywindow["exports"] = _exports; //2兼容 exports
                        anywindow["module"] = { exports: _exports } //3兼容 exports
                        {
                            window.eval(nextfile);
                        }
                        //console.log("setmodule=" + fullurl);

                        this.modules[fullurl] = _exports;
                    }
                }
            }
        }


        static async loadmain(url: string, _useScript: boolean = false): Promise<void>
        {
            let _exports = {};
            anywindow["exports"] = _exports; //2兼容 exports
            anywindow["module"] = { exports: _exports } //3兼容 exports


            console.log("require.loadmain = " + url);
            let entryfile = await (await fetch(url)).text();

            await require.ParseModule("./", entryfile);

            //let entry go.

            require.getModulePath = "./";
            if (_useScript)
            {
                await require.loadScript(url);
            }
            else
            {
                window.eval(entryfile);
            }
            console.log("require.loadmain end,and dispath window.onload here.");
            require.DispathWindowOnload();
        }
        static getModulePath: string = "";
        static GetModule(url: string): Object
        {
            console.log("GetModule " + url + " from " + require.getModulePath);
            let name = require.MixPath(require.getModulePath, url);
            return require.modules[name];
        }
        static modules: { [id: string]: Object } = {};
    }

}
//1.兼容global
anywindow["global"] = window;
//4.兼容require
anywindow["require"] = letus.require.GetModule;